import store from 'store'
import Cookies from 'js-cookie'

/**
 * 代理服务
 */
export const baseUrl = '/s'

/**
 * 数据请求
 * @param {string} uri
 * @param {object} params
 */
export function pipeline(uri, params, opt = {}) {
  const sUrl = toRealUrl(uri)
  const headers = new Headers()
  headers.append('X-Requested-With', 'XMLHttpRequest')
  headers.append('Accept', '*/*')
  // headers.append('Content-Type', 'application/x-www-form-urlencoded')
  return fetch(sUrl, {
    credentials: 'include',
    method: 'post',
    headers,
    body: parseBody(params),
    ...opt,
  }).then(res => {
    if (res.status >= 400) throw res
    try {
      return res.json()
    } catch (err) {
      throw res
    }
  })
}

/**
 * uri 转 url
 * @param {*} uri
 */
export function toRealUrl(uri) {
  return /^:/.test(uri) ? `${baseUrl}/${uri.replace(':', '')}` : uri
}

/**
 * 请求参数处理
 * @param {object} params
 */
export function parseBody(params = {}) {
  const auth = store.get('m:auth') || {}
  if(Cookies.get('ticket') || auth.user_ticket) {
    Cookies.set('ticket', Cookies.get('ticket') || auth.user_ticket)
  }
  params = {
    ...params,
    user_ticket: auth.user_ticket || Cookies.get('ticket'),
  }
  const formData = new FormData()
  Object.keys(params).forEach((key) => {
    formData.append(key, params[key] instanceof Blob ? params[key] : (String(params[key]) || ''))
  })
  return formData
}
